package com.gmlive.common.host.retrofit

import android.os.Build
import android.os.HandlerThread
import android.util.Log
import com.gmlive.common.host.BuildConfig
import com.gmlive.common.host.manager.HostUpdateManager
import com.gmlive.common.host.server.IApi
import org.json.JSONObject

/**
 * Created by ZhongJianXin
 * on 2019-10-23
 * desc
 */
class HostReqThread(name: String, private val ip: String) : HandlerThread(name) {

    private val TAG = "HostReqThread"

    override fun onLooperPrepared() {
        super.onLooperPrepared()
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "$name onLooperPrepared:$ip${HostUpdateManager.ins().url}")
        }
        doRequestHost(ip)
    }

    private fun doRequestHost(ip: String) {
        RetrofitCreateHelper.createApi2String(ip, IApi::class.java)
                .requestHostUpdate("$ip${HostUpdateManager.ins().url}", HostUpdateManager.ins().key)
                .enqueue(object : BaseCallback<String>() {
                    override fun onSuccess(t: String?) {
                        if (BuildConfig.DEBUG) {
                            Log.w(TAG, "$name onSuccess:$ip${HostUpdateManager.ins().url}")
                        }
                        if (t != null) {
                            val jsonObject = JSONObject(t)
                            HostUpdateManager.ins().setServerMap(jsonObject.optString("data"))
                        }
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            quitSafely()
                        } else {
                            quit()
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        if (BuildConfig.DEBUG) {
                            Log.w(TAG, "$name onFailed:$ip${HostUpdateManager.ins().url} code:$code error:$msg")
                        }
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            quitSafely()
                        } else {
                            quit()
                        }
                    }
                })
    }

    override fun quit(): Boolean {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "$name quit:$ip${HostUpdateManager.ins().url}")
        }
        return super.quit()
    }

    override fun quitSafely(): Boolean {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "$name quitSafely:$ip${HostUpdateManager.ins().url}")
        }
        return super.quitSafely()
    }
}